package com.example.service.impl;

import com.example.entity.Book;
import com.example.entity.BorrowRecord;
import com.example.mapper.BookMapper;
import com.example.mapper.BorrowRecordMapper;
import com.example.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月06日15:11
 */
@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private BorrowRecordMapper borrowRecordMapper;

    @Override
    public List<Book> listAll() {
        return bookMapper.findAll();
    }

    @Override
    public Book getById(Integer id) {
        return bookMapper.findById(id);
    }

    @Override
    public void addBook(Book book) {
        bookMapper.insert(book);
    }

    @Override
    public void updateBook(Book book) {
        bookMapper.update(book);
    }

    @Override
    public void deleteBook(Integer id) {
        bookMapper.delete(id);
    }

    @Override
    @Transactional
    public boolean borrowBook(Integer bookId, Integer userId) {
        Book book = bookMapper.findById(bookId);
        if (book == null || book.getStock() <= 0) {
            return false;
        }

        // 更新库存
        book.setStock(book.getStock() - 1);
        bookMapper.updateBook(book);

        // 添加借阅记录
        BorrowRecord record = new BorrowRecord();
        record.setUserId(userId);
        record.setBookId(bookId);
        record.setBorrowDate(new Date());
        borrowRecordMapper.insert(record);

        return true;
    }

}
